package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.AgriculturalForumTopicListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompanyForumTopic;
import com.isunland.managesystem.entity.CompanyForumType;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.Expert;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

/**
 * 对象功能:  话题列表
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/3/16 15:16
 */
public class AgriculturalForumListFragment extends BaseListFragment
    implements View.OnClickListener {
  public static final String EXTRA_VALUE =
      "com.isunland.managesystem.ui.AgriculturalForumListFragment.EXTRA_VALUE";

  public static final String EXTRA_TOPIC_QUERY = "com.isunland.managesystem.ui.EXTRA_TOPIC_QUERY";
  public static final String EXTRA_QUERY_TYPE = "com.isunland.managesystem.ui.EXTRA_QUERY_TYPE";

  //帖子列表来源
  public static final String EXTRA_FROM =
      "com.isunland.managesystem.ui.AgriculturalForumListFragment.EXTRA_FROM";
  //帖子人员 jobno
  public static final String EXTRA_JOBNO =
      "com.isunland.managesystem.ui.AgriculturalForumListFragment.EXTRA_JOBNO";
  //帖子人员 name
  public static final String EXTRA_NAME =
      "com.isunland.managesystem.ui.AgriculturalForumListFragment.EXTRA_NAME";

  public static final String TYPE = "type";//来自作物分类的帖子
  public static final String PERSON = "person";//按人查询: 我的好友
  public static final String EXPERT = "expert";//专家
  public static final String COLLECT = "collect";//我收藏帖子
  public static final String NEED = "need";//待回复的帖子
  public static final String SELF = "self";//自己发布的帖子
  public static final String COLLECT_TYPE = "collect_type";//收藏分类的帖子
  public static final String CIRCLE = "CIRCLE";//朋友圈子成员发布的所有帖子

  private static final int REQUEST_ADD = 0;
  private static final int REQUEST_DELETE = 1;
  private static final int REQUEST_SELECT = 3;// 筛选
  private AgriculturalForumTopicListAdapter mAdapter;

  private String mBeginDate;// 查询话题的开始时间
  private String mEndDate;// 查询话题的结束时间
  private String mStaffName;
  private String mQuery;
  private CompanyForumType mCompanyType;
  private CurrentUser mCurrentUser;
  private String mFrom;
  private String mJobno;
  private String mName;
  private ArrayList<CompanyForumTopic.actualObject> mList;

  @Override public void initData() {
    super.initData();
    mCompanyType = (CompanyForumType) getArguments().getSerializable(EXTRA_VALUE);
    mFrom = getArguments().getString(EXTRA_FROM);
    mJobno = getArguments().getString(EXTRA_JOBNO);
    mName = getArguments().getString(EXTRA_NAME);
    if (mCompanyType != null && mCompanyType.getName() != null) {
      setTitleCustom(mCompanyType.getName());
    }
    mCurrentUser = CurrentUser.newInstance(getActivity());
    mList = new ArrayList<>();
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    if (EXTRA_TOPIC_QUERY.equals(mQuery)) setTitleCustom(R.string.topiclist);
    //int padding = MyUtils.dip2px(getActivity().getApplicationContext(), 10);
    //mListview.setDivider(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
    //mListview.setDividerHeight(padding);
    //mListview.setPadding(padding, 0, padding, padding);
    mListview.setDividerHeight(0);

    if (TYPE.equalsIgnoreCase(mFrom)   //具体作物帖子
        || EXPERT.equalsIgnoreCase(mFrom)  //专家发布的帖子
        || COLLECT_TYPE.equalsIgnoreCase(mFrom)  //收藏分类下的帖子
        || SELF.equalsIgnoreCase(mFrom))  //我发布的帖子
    {
      //我要提问,我要发帖
      TextView tvAsk = (TextView) view.findViewById(R.id.tv_ask);
      TextView tvPublish = (TextView) view.findViewById(R.id.tv_publish);
      tvAsk.setOnClickListener(this);
      tvPublish.setOnClickListener(this);
    }
  }

  @Override protected String setEmptyText() {
    String message;
    if (EXTRA_TOPIC_QUERY.equals(mQuery)) {
      message = getResources().getString(R.string.thisStaffNoTopic);
    } else {
      message = getResources().getString(R.string.noTopicPublish);
    }
    return message;
  }

  /**
   * 添加发布按钮
   */
  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //具体作物圈下的帖子可发布新话题,专家列表,收藏分类.
    if (TYPE.equalsIgnoreCase(mFrom)) {
      inflater.inflate(R.menu.menu_wjforum_publish, menu);
    }
    //我的话题,可以发布话题
    if (SELF.equalsIgnoreCase(mFrom)) {
      inflater.inflate(R.menu.menu_forum_publish, menu);
      menu.getItem(1).setVisible(false);
    }
    //收藏分类下帖子:  查询,取消收藏,专家列表
    if (COLLECT_TYPE.equalsIgnoreCase(mFrom)) {
      inflater.inflate(R.menu.menu_forum_cancle, menu);
    }
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public String getUrl() {
    //具体作物帖子
    if (TYPE.equalsIgnoreCase(mFrom)) {
      return ApiConst.URL_KNOWLEDGEFORUM_POST_LIST;
    } else
      //收藏分类的帖子
      if (COLLECT_TYPE.equalsIgnoreCase(mFrom)) {
        return ApiConst.URL_KNOWLEDGEFORUM_POST_LIST;
      } else
        //我收藏的帖子
        if (COLLECT.equalsIgnoreCase(mFrom)) {
          return ApiConst.URL_COLLECT_TOPIC;
        } else
          //好友发布的帖子,我发布的帖子,专家发布的帖子
          if (PERSON.equalsIgnoreCase(mFrom)
              || SELF.equalsIgnoreCase(mFrom)
              || EXPERT.equalsIgnoreCase(mFrom)) {
            return ApiConst.URL_PERSON_TOPIC_LIST;
          } else
            //待回复的帖子
            if (NEED.equalsIgnoreCase(mFrom)) {
              return ApiConst.URL_NEED_ANSWER_TOPIC;
            } else
              //朋友圈成员的帖子
              if (CIRCLE.equalsIgnoreCase(mFrom)) {
                return ApiConst.URL_CIRCLE_TOPIC;
              } else {
                //返回空,会报错.默认给个地址
                return ApiConst.URL_KNOWLEDGEFORUM_POST_LIST;
              }
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    //具体作物帖子
    if (TYPE.equalsIgnoreCase(mFrom) || COLLECT_TYPE.equalsIgnoreCase(mFrom)) {
      if (EXTRA_TOPIC_QUERY.equals(mQuery)) {
        if (mBeginDate != null && mEndDate != null) {
          params.put("beginregDate", mBeginDate + " 00:00:00");
          params.put("endregDate", mEndDate + " 23:59:59");
        }
      }

      if (mCompanyType != null && mCompanyType.getCustomAttrs() != null) {
        params.put("topicKindCode", mCompanyType.getCustomAttrs());
      }
      params.put("orderField", "discuss_Count DESC,REG_DATE");
      params.put("orderSeq", "DESC");
    }
    //我收藏的帖子
    if (COLLECT.equalsIgnoreCase(mFrom)) {
      params.put("jobno", mJobno);
      /** 01: 农技服务,02: 农机服务*/
      params.put("topicKindCode",
          SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""));
    }
    //好友发布的帖子,我发布的帖子,专家发布的帖子
    if (PERSON.equalsIgnoreCase(mFrom) || SELF.equalsIgnoreCase(mFrom) || EXPERT.equalsIgnoreCase(
        mFrom)) {
      params.put("jobNo", mJobno);
      /** 01: 农技服务,02: 农机服务*/
      params.put("topicKindCode",
          SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""));
    }
    //待回复的帖子
    if (NEED.equalsIgnoreCase(mFrom)) {
      params.put("topicKindCode",
          SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""));
    }
    //朋友圈成员发布的帖子
    if (CIRCLE.equalsIgnoreCase(mFrom)) {
      params.put("mainid", mJobno);
    }
    return params.getParams();
  }

  @Override public void resolveResponse(String arg0) {
    CompanyForumTopic topicList = new Gson().fromJson(arg0, CompanyForumTopic.class);
    mList.clear();
    //具体作物分类下的帖子或我发布的帖子,专家发布的帖子,我收藏的帖子
    mList.addAll(
        (TYPE.equalsIgnoreCase(mFrom) || COLLECT_TYPE.equalsIgnoreCase(mFrom)) ? topicList.getData()
            : topicList.getRows());
    mAdapter = new AgriculturalForumTopicListAdapter(mActivity, mList);
    setListAdapter(mAdapter);
    //mAdapter.notifyDataSetChanged();

  }

  /**
   * 跳转到话题回复列表
   */
  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    CompanyForumTopic.actualObject topicContent = mAdapter.getItem(position - 1);
    //        Intent intent = new Intent(getActivity(), KnowledgeForumPostDetailAcrivity.class);
    //        intent.putExtra(KnowledgeForumPostDetailFragment.EXTRA_VALUE, topicContent);
    //        startActivityForResult(intent, REQUEST_DELETE);
    Intent intent = new Intent(getActivity(), AgriculturalForumDetailAcrivity.class);
    intent.putExtra(AgriculturalForumDetailFragment.EXTRA_VALUE, topicContent);
    intent.putExtra(AgriculturalForumDetailFragment.EXTRA_FROM, mFrom);
    startActivityForResult(intent, REQUEST_DELETE);

    super.onListItemClick(l, v, position, id);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    Intent intent;
    switch (item.getItemId()) {
      /**
       * 响应返回按钮
       */
      case android.R.id.home:
        getActivity().finish();
        return true;

      case R.id.menu_item_publish:
        // 跳到发布话题页面
        if (mCompanyType != null) {
          //                    intent = new Intent(getActivity(), KnowledgeForumTopicPublishActicity.class);
          //                    intent.putExtra(EXTRA_FORUM_TYPE, mCompanyType);
          //                    startActivityForResult(intent, REQUEST_ADD);

          intent = new Intent(getActivity(), AgriculturalTopicPublishActicity.class);
          intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_FORUM_TYPE, mCompanyType);
          if (SELF.equalsIgnoreCase(mFrom)) {
            intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_TYPE,
                AgriculturalTopicPublishFragment.SELF);
          }
          startActivityForResult(intent, REQUEST_ADD);
        }
        return true;
      // 按照条件进行查询：按发布人户发布时间
      case R.id.menu_item_topic_search:
        intent = new Intent(getActivity(), KnowledgeforumTopicQueryActicity.class);
        intent.putExtra(KnowledgeforumTopicQueryFragment.REQUEST_STAFF_NAME, mStaffName);
        intent.putExtra(KnowledgeforumTopicQueryFragment.REQUEST_START_DATE, mBeginDate);
        intent.putExtra(KnowledgeforumTopicQueryFragment.REQUEST_END_DATE, mEndDate);
        startActivityForResult(intent, REQUEST_SELECT);
        return true;
      case R.id.menu_item_collection:
        //收藏分类
        volleyPostAddCollect();
        return true;

      case R.id.menu_item_cancel:
        //取消收藏分类
        volleyPostCancleCollect();
        return true;

      case R.id.menu_item_expert:
        //获取专家列表
        //和我关注的专家是一个页面
        Intent expert = new Intent(getActivity(), AgriculturalMyExpertListActivity.class);
        expert.putExtra(AgriculturalMyExpertListFragment.EXTAR_TYPE, mCompanyType);
        startActivity(expert);
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  /*取消收藏*/
  private void volleyPostCancleCollect() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MY_COLLECTION_CANCLE);
    HashMap<String, String> params = new HashMap<>();
    params.put("collecttypecode", mCompanyType.getCustomAttrs());
    MyUtils.showDialogLoading(getActivity(), R.string.cancleCollect);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {
            ToastUtil.show("取消收藏成功");
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }
    });
  }

  /* 添加收藏分类**/
  private void volleyPostAddCollect() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_MY_COLLECTION_ADD);
    HashMap<String, String> params = new HashMap<>();
    params.put("jobno", mCurrentUser.getJobNumber());
    params.put("collecttypecode", mCompanyType.getCustomAttrs());
    params.put("collecttypename", mCompanyType.getName());
    params.put("collectid", "");
    MyUtils.showDialogLoading(getActivity(), R.string.collectionType);
    mActivity.volleyPost(url, params, new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        try {
          MyUtils.dismissDialog();
          //解析
          SuccessMessage result = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == result || null == result.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = result.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(result.getMessage());
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {

            ToastUtil.show(R.string.success_operation);
          }
        } catch (JsonSyntaxException e) {
          ToastUtil.show(R.string.wrong_data);
        }
      }
    });
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    if (requestCode == REQUEST_SELECT) {
      mBeginDate = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_BEGIN_DATE);
      mEndDate = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_END_DATE);
      mQuery = data.getStringExtra(EXTRA_QUERY_TYPE);
      mStaffName = data.getStringExtra(KnowledgeforumTopicQueryFragment.EXTRA_STAFF_NAME);
    }

    volleyPost();

    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override public void initMockData() {
    super.initMockData();
    mFrom = TYPE;
  }

  /** 重新自定义界面 */
  @Override protected int setCustomLayoutId() {

    if (TYPE.equalsIgnoreCase(mFrom)   //具体作物帖子
        || EXPERT.equalsIgnoreCase(mFrom)  //专家发布的帖子
        || COLLECT_TYPE.equalsIgnoreCase(mFrom)  //收藏分类下的帖子
        || SELF.equalsIgnoreCase(mFrom))  //我发布的帖子
    {
      return R.layout.fragment_forum_list;
    } else {
      return super.setCustomLayoutId();
    }
  }

  @Override protected int setCustomtListViewId() {
    if (TYPE.equalsIgnoreCase(mFrom)   //具体作物帖子
        || EXPERT.equalsIgnoreCase(mFrom)  //专家发布的帖子
        || COLLECT_TYPE.equalsIgnoreCase(mFrom)  //收藏分类下的帖子
        || SELF.equalsIgnoreCase(mFrom))  //我发布的帖子
    {
      return R.id.lv_pullToRefresh;
    } else {
      return super.setCustomtListViewId();
    }
  }

  @Override public void onClick(View view) {
    // 跳到发布话题页面
    Expert mExpertContent = new Expert();
    mExpertContent.setMembername(mName);
    mExpertContent.setJobno(mJobno);
    Intent intent = new Intent(getActivity(), AgriculturalTopicPublishActicity.class);

    switch (view.getId()) {

      case R.id.tv_ask:
        //我要提问
        if (mCompanyType != null) {
          intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_FORUM_TYPE, mCompanyType);
        }
        if (SELF.equalsIgnoreCase(mFrom) || EXPERT.equalsIgnoreCase(mFrom)) {
          //显示圈子类别
          intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_TYPE,
              AgriculturalTopicPublishFragment.SELF);
        }
        if (EXPERT.equalsIgnoreCase(mFrom)) {
          //咨询专家,@专家信息
          intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_FROM, mExpertContent);
        }
        break;

      case R.id.tv_publish:
        //发帖: 不限制条件
        intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_FORUM_TYPE, mCompanyType);
        intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_TYPE,
            AgriculturalTopicPublishFragment.SELF);
        break;
      default:
        break;
    }
    startActivityForResult(intent, REQUEST_ADD);

    // 跳到发布话题页面
    //Expert mExpertContent = new Expert();
    //mExpertContent.setMembername(mName);
    //mExpertContent.setJobno(mJobno);
    //Intent intent = new Intent(getActivity(), AgriculturalTopicPublishActicity.class);
    //if (mCompanyType != null) {
    //  intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_FORUM_TYPE, mCompanyType);
    //}
    //if (SELF.equalsIgnoreCase(mFrom) || EXPERT.equalsIgnoreCase(mFrom)) {
    //  //显示圈子类别
    //  intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_TYPE,
    //      AgriculturalTopicPublishFragment.SELF);
    //}
    //if (EXPERT.equalsIgnoreCase(mFrom)) {
    //  //咨询专家,@专家信息
    //  intent.putExtra(AgriculturalTopicPublishFragment.EXTRA_FROM, mExpertContent);
    //}
    //startActivityForResult(intent, REQUEST_ADD);
  }

  public static AgriculturalForumListFragment newInstance(CompanyForumType type, String from,
      String jobno) {
    return newInstance(type, from, jobno, "");
  }

  public static AgriculturalForumListFragment newInstance(CompanyForumType type, String from,
      String jobno, String name) {
    Bundle bundle = new Bundle();
    bundle.putSerializable(EXTRA_VALUE, type);
    bundle.putString(EXTRA_FROM, from);
    bundle.putString(EXTRA_JOBNO, jobno);
    bundle.putString(EXTRA_NAME, name);
    AgriculturalForumListFragment fragment = new AgriculturalForumListFragment();
    fragment.setArguments(bundle);
    return fragment;
  }
}

